% nbc=nbayes_train(TRAIN,OBJECTIVE)
% Estimates the mean value and variance of a gaussian
% distribution to describe a naive bayes classifier for a 
% multi class problem.
% TRAIN must be a 2d-matrix where each row represents 
% a vector of class attributes (train sample).
% OBJECTIVE represents the class labels where zero labels are ignored
% The classifier information is included in the structure nbc:
% nbc(n).meanC - estimate of the mean for each attribute of class n
% nbc(n).varC - estimate of the variance for each attribute of class n
%
% see alco: nbayes_test

function nbc=nbayes_train(TRAIN,OBJECTIVE)

if nargin ~= 2, error('Number of arguments not valid.'); end
if size(TRAIN,1)~=length(OBJECTIVE), 
    error('Number of train samples must be equal to number of class labels.');
end

zeroLabel=OBJECTIVE==0;
OBJECTIVE(zeroLabel)=[];
TRAIN(zeroLabel,:)=[];

EPSILON = 5e-13;

classes = unique(OBJECTIVE);

% if ~all(diff([0;classes])==1),
%     warning('Data must be labeled from 1:nclasses');
% end

for k=1:length(classes),
    nbc(k).label = classes(k);
    % get indices for different classes
    idx = find(OBJECTIVE==classes(k));
    % calculate mean estimates of classes
    nbc(k).meanC = mean(TRAIN(idx,:));

    % calculate variance estimates of classes
    nbc(k).varC = var(TRAIN(idx,:));

    nbc(k).varC(find(nbc(k).varC<EPSILON))=EPSILON;
end